/**
 * 错误处理
 */
import * as Koa from 'koa';
import { fail } from './result'
import logger from './logger';
import * as log from './logger';
import { mongooseModelError, Exceptions } from '../kalend';

export default async (ctx: Koa.Context, next: any) => {

    try {
        const start: any = new Date();

        await next();
        const end: any = new Date();
        const ms = end - start;
        let requesttime = {
            starttime: start,
            endtime: end,
            mstime: ms
        }
        log.weritelog(ctx,requesttime);
        mongooseModelError.emit();
    } catch (err) {
        mongooseModelError.emit(false);

        ctx.status = 200;
        if (err.message === "session store is unavailable") {
            err = Exceptions.redisServiceStop(err);
        }
        let msg: String;
        let errcode: any;
        let original: Error;
        if (err.kalend) {
            msg = err.message;
            errcode = err.kalend.code;
            if (err.kalend.original) {
                original = err.kalend.original;
            }
        } else {
            msg = "未知异常";
            errcode = -1;
            original = err;
        }
        const log = logger(ctx);
        if (original) {
            // TODO:写日志
            log.error(original);
        } else {

        }
        ctx.body = fail(msg, errcode);
    }
}